package com.pjedu.nbmallshop.service.imp;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.pjedu.nbmallshop.entity.MallOrder;
import com.pjedu.nbmallshop.service.MallOrderService;
import com.pjedu.nbmallshop.service.PayService;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {
    //APPID
    private final static String APP_ID = "2021000119609126";
    //应用私钥
    private final static String APP_PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCpJNIy1S1+BZrr2TqaW9+3HWFTbRxVSLS3sKWs1BO/C4NNAFEbWMNJtf5koDFQoEtDYDXHvRoPu81bBdyaih5o5bJWXEcE5pI9iF8EAqCxc25yNIpAbsNG+0qBLE+lJBF+l9XoDv0k4KsRXwpR/LztB+7lBK3lcemh2lSxv7SQ+pqR9xd/2yScshpGJMT+dQy51t+gbikoJqUirGjCmcYdv42Z9zStteotcGYNkvjOzZBtfNrS/uoLD9RXPwS1IJBMp2i9eE9hBryPgxhUjIa3BxTzoeC9AL/xgkFmIO9ZlOJiRicy9JO+TtoCWCu41/wMO7VLFu+6nh3vD416OVynAgMBAAECggEAVyYgo45RFTiAHPrdBgFGYEvkBJ8YVRzT+D0s78KJtgqRiVAbehKe9FCwFVqwbhFZFgrxSsu1LNwfr8Fya7G0f2myHGsJMI44VTn5ctCDyUpnYrKNdStctCrvtWSGWNkfpnFHBn0Kk0CrA5VLdPjawuoufZOOocSykvEyaC8VMwkFvcE9OAWwAOaIsADKf+YFF+gdltIndtGrQuLnC+nu40OYK2I/Tq4F/NrGI6tJrHMZc5BGEc4G4dA3ny/zpaS6Z5J/FTH5Ot8BYQxJLQoLBvLLw/K4e0Ef6wzfP36j9I4MYU18667dwkBoo4pPvBXXBzNlhohGQqMtT5Opjddj0QKBgQDS0iif+LcVyfGVt73J/2U19RHeyeKh9K0AvAkF4zptKtvzVMqMxRaM2XFIRxswKIDXVvS0UPA8qzF2P7RgheyvP5F0g/rZ9Lg0Kte5qkP3vxftoYftmNA4brbDaDp3V3exSyWkewTzCDwH4P9Qeuf98k1lOFz2H3T81i4+Q+xRjwKBgQDNZDdXE+HN3JS7H3Pyx84QJRypsNRl52cY+bNI7ES9BXWzKPYE8qCeNdrW6pzU0ddZWmMcU17cMr5bEF2AziK0+nWG/pzddKzAilnxt+2ghumbMEzJgyQ/CB9VDLUgNu0BTWU592a6SjReg8qgvbmBIyd6dgs70ooK0zMx3F8HaQKBgBO93FIGn1Zp/7Zua1ZUFS01UsQTEabq25x6/zlO6vS4E7q4kPMXraHo5sPG7NPYpyADI40TGzwDJ/GTy5dSUzSh9kP76+ynDuzLqkHXoN+9REdbXfgw3Ca8r16jDv6H8Uxn5hF995uuhLiUKDRoHftYykiVO5dMoM7gW5o3EBUfAoGAIetF9Fx1MvEVot1r4ZE7p5DpbeClAvs3HHnIMOfL5kdri53dGy4Sdm5AaLOwGLlazgfOTFQ8WzMKGrHWLzpbovWlyRhtQWlOSjHO7stIM/VzyMwuMi01JC+sNPh3RQ2tEET+zZbc4TD1+xHaubb7Vqc+ksvBySxY3bbJQpe5HdkCgYBORwzyfHrG07DTE570/FTMGmd4LPIAW5UeLmJsphGBQGLkhtlDmS5CIwddlYmeT9hZBlDpHZ2cF7FKwzWLUcd0vcyZjytflnCd+ZMYJCsfony0tnhcebZVIBj6+s+KIn7QEf85ZXpExL/c5Xvzq+Z37DuBKRNuHBxN8d8DZG5V9Q==";
    private final static String CHARSET = "UTF-8";
    //阿里公钥
    private final static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhsWkhwLUzK+urxQxW/Z8I8BLypRVXAJ3iQF1BsT1qcx5VP3Y8IoxjDJGViIUXGblSfL1uiUTmbtj5fVNwMUdKnWjoR22H/zs4zDfaBdSyF0T9fRnR9iQkZ3omw4n2NyhrdtE6VLvwAlZolNapTBWUC5cURmcujw6nzrObZJzlGsvQPCAJb6Sct0AUIKGxO45N9Ixjp47Ddu8oy4TEzmDlGjzYBw6SapisqzrLkkL8Lk1fpr4d21p/NFz3c3jnhJXpUZE8xRrJGV+Cv/v6hqjPMOduLmbCae9S3Gv20exuT0vwsW02PnP8yRO2zjwKuX7v3NZBpaoaqz2m/sMfauPowIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final static String GATEWAY_URL = "https://openapi.alipaydev.com/gateway.do";
    private final static String FORMAT = "JSON";
    //签名方式
    private final static String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址【自己测试的时候不方便】
    private final static String NOTIFY_URL = "http://公网地址/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final static String RETURN_URL = "http://localhost:8080/paySuccess";
    //实例化客户端,填入所需参数
    private final static AlipayClient alipayClient =
            new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);

    @Resource
    private MallOrderService mallOrderService;

    @Override
    public String aliapyForm(String orderNo) {
        //根据订单编号,查询订单相关信息
        MallOrder mallOrder = mallOrderService.getMallOrderByOrderNo(orderNo);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        // request.setNotifyUrl(NOTIFY_URL); 不设置

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = mallOrder.getOrderNo();
        //付款金额，必填
        String total_amount = mallOrder.getTotalPrice().toString();
        //订单名称，必填
        String subject = "NB商城订单";
        //详情描述，可空
        String body = "";
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    @Override
    public String alipayCheck(Map<String, String> params) throws AlipayApiException {
        // boolean signVerified = AlipaySignature.rsaCheckV2(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //因为我们使用的是系统默认的加签方式,所以使用V1,如果你是自己配置的签名的话,那么就选择V2
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过 - 这代表此消息是支付宝返回的
        // 紧接着，通过接口同步查询一下是不是真的付款了
        if (signVerified) {
            // 商户订单号
            String out_trade_no = params.get("out_trade_no");
            // 支付宝交易号
            String trade_no = params.get("trade_no");

            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + out_trade_no + "\"," +
                    "\"trade_no\":\"" + trade_no + "\"" +
                    "  }");
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess() && ("TRADE_SUCCESS".equals(response.getTradeStatus()))) {
                return out_trade_no;
            }
        } else {
            throw new AlipayApiException("非法请求，验签不通过");
        }
        return null;
    }
}
